<template>
  <el-cascader
    v-model="cascade_value"
    clearable
    :props="cascade_props"
    :options="caseOptions"
    ref="myAreaSel"
    @change="handlerCascadeChange"
    @input.native="inputEnter"
    style="width: 100%"
    :size="size"
  >
    <!--<template slot-scope="{ node, data }">
        <span>{{ data['extName'] || data['name'] }}</span> filterable
        </template>-->
  </el-cascader>
</template>

<script>
import { rootNode, childenNode, filterByKey } from '@/api/public/areaSelector'
export default {
  name: 'EAreaSelector',
  props: {
    value: {
      type: Array,
      default: []
    },
    areaLevel: {
      type: Number,
      default: 3
    },
    size: {
      type: String,
      default: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      async handler (val) {
        console.log('watchvalue', val)
        if (val && val.length > 0) {
          let pcode = val[0].substr(0, 2) + '0000'
          let pt = await this.initRoot()
          this.proviceList = pt
          let postion = []
          let postionvalue = []
          let datanode = []
          let fstIndex = 0
          if (pt.length > 0) {
            this.proviceList = pt
            pt.forEach((v, index) => {
              let pmap = {
                value: v.id + '',
                label: v.name + '',
                id: v.id + '',
                latitude: v.latitude + '',
                longitude: v.longitude + ''
              }
              if (this.areaLevel > 1) {
                pmap.children = []
              }
              pmap.leaf = this.areaLevel === 1
              datanode.push(pmap)
              if (v.id === pcode) {
                fstIndex = index
                postionvalue.push(v.id)
                postion.push(index)
              }
            })
          }
          let secode = val[0].substr(0, 4) + '00'
          if (this.areaLevel > 1) {
            let slist = await this.getChildren(pcode)
            let sdataNode = []
            if (slist.length > 0) {
              slist.forEach((vi, index2) => {
                let pmap = {
                  value: vi.id + '',
                  id: vi.id + '',
                  label: vi.name + '',
                  latitude: vi.latitude + '',
                  longitude: vi.longitude + ''
                }
                if (this.areaLevel > 2) {
                  pmap.children = []
                }
                pmap.leaf = this.areaLevel === 2
                sdataNode.push(pmap)
                if (vi.id === secode) {
                  postion.push(index2)
                  postionvalue.push(vi.id)
                }
              })
            }
            datanode[postion[0]].children = sdataNode
          }
          if (this.areaLevel > 2) {
            let thirdLeve = await this.getChildren(secode)
            let fdataNode = []
            if (thirdLeve.length > 0) {
              thirdLeve.forEach((vi, index3) => {
                fdataNode.push({
                  value: vi.id + '',
                  id: vi.id + '',
                  label: vi.name + '',
                  latitude: vi.latitude + '',
                  longitude: vi.longitude + '',
                  leaf: true
                })
                if (vi.id === val[0]) {
                  postion.push(index3)
                  postionvalue.push(vi.id)
                }
              })
              datanode[postion[0]].children[postion[1]].children = fdataNode
            }
          }
          this.cascade_value = postionvalue
          this.caseOptions = datanode
          console.log('123', postionvalue)
          console.log('1234', datanode)
        } else {
          this.cascade_value = []
          this.caseOptions = []
        }
      }
    }
    // value (val) {
    //   console.log('valval', val)
    //   if (val == null) {
    //     this.childSelectedValue = []
    //   } else {
    //     this.cascade_value = val
    //   }
    // }
  },
  data () {
    const self = this
    return {
      cascade_value: [],
      caseOptions: [],
      //cascade_options: [],
      cascade_props: {
        lazy: true,
        // emitPath: false,
        //checkStrictly: true, //可以选择任意节点
        expandTrigger: 'click', //click/hover
        async lazyLoad (node, resolve) {
          console.log('node', node)
          const { data, level } = node
          if (level == 0) {
            const resultData = await rootNode()
            if (resultData.code === 0 && resultData.data.bcode === 0) {
              self.proviceList = resultData.data.bdata
              const nodes = resultData.data.bdata.map(item => ({
                value: item['id'],
                label: item['name'],
                id: item['id'],
                leaf: level >= self.areaLevel - 1
              }))
              resolve(nodes)
            } else {
              resolve([])
            }
          } else if (level == self.areaLevel) {
            resolve([])
          } else {
            const pid = data ? data['id'] : 0
            const resultData = (await childenNode(pid)) || []
            if (resultData.code === 0 && resultData.data.bcode === 0) {
              if (level === 1) {
                self.cityList = resultData.data.bdata
              } else {
                self.areaList = resultData.data.bdata
              }
              const nodes = resultData.data.bdata.map(item => ({
                value: item['id'],
                label: item['name'],
                id: item['id'],
                leaf: level >= self.areaLevel - 1
              }))
              resolve(nodes)
            }
          }
        }
      },
      proviceList: [],
      cityList: [],
      areaList: [],
      valueModel: {
        code: null,
        name: null,
        lat: null,
        lng: null
      },
      valueList: []
    }
  }, //data
  methods: {
    async initRoot () {
      const resultData = await rootNode()
      if (resultData.code === 0 && resultData.data.bcode === 0) {
        return resultData.data.bdata
      } else {
        return []
      }
    },
    async getChildren (pid) {
      const resultData = (await childenNode(pid)) || []
      if (resultData.code === 0 && resultData.data.bcode === 0) {
        return resultData.data.bdata
      } else {
        return []
      }
    },
    async inputEnter () {
      let ref = this.$refs['myAreaSel']
      console.log('ref', ref)
      setTimeout(() => {
        console.log('inputValue', ref.inputValue)
        if (ref.inputValue) {
          let param = { keywords: ref.inputValue, level: '1' }
          filterByKey(param).then(res => {
            console.log('pt', res)
          })

          param = { keywords: ref.inputValue, level: '2' }
          filterByKey(param).then(res2 => {
            console.log('pt2', res2)
          })

          param = { keywords: ref.inputValue, level: '3' }
          filterByKey(param).then(res3 => {
            console.log('pt3', res3)
          })
        }
      })
    },
    //级联选择器——change
    handlerCascadeChange (value) {
      this.valueList = []
      if (value.length) {
        let node = this.$refs.myAreaSel.getCheckedNodes()[0]
        let pt = { ...this.valueModel }
        pt.code = value[0]
        let fs = this.proviceList.filter(item => {
          return item.id == pt.code
        })

        pt.name = fs[0].name
        this.valueList.push(pt)
        if (node.level === 2) {
          pt = []
          pt = { ...this.valueModel }
          pt.code = value[1]
          pt.name = node.data.label
          this.valueList.push(pt)
        } else if (node.level === 3) {
          pt = []
          pt = { ...this.valueModel }
          pt.code = value[1]
          pt.name = node.parent.data.label
          this.valueList.push(pt)
          pt = []
          pt = { ...this.valueModel }
          pt.code = value[2]
          pt.name = node.data.label
          this.valueList.push(pt)
        }
      }
      this.$emit('selObj', this.valueList)
      console.log('valueListvalueList', this.valueList)
    }
  }
}
</script>

<style scoped></style>
